<template>
    <v-card>
        <v-card-title>
            <v-text-field
                    v-model="search"
                    prepend-icon="search"
                    label="搜索歌曲"
                    single-line
                    hide-details
            ></v-text-field>
            <v-spacer></v-spacer>
            <v-flex xs2>
                <v-btn round color="primary" dark @click="addSong">
                    新增歌曲
                </v-btn>
            </v-flex>
        </v-card-title>
        <v-data-table
                :headers="headers"
                :items="songs"
                :pagination.sync="pagination"
                :total-items="totalSongs"
                :loading="loading"
                class="elevation-1"
        >
            <template v-slot:items="props">
                <td>{{ props.item.id }}</td>
                <td class="text-xs-center">
<!--                    <img :src="props.item.image">-->
                <div class="imPlay">
                    <!--头像图片-->
<!--                    <img :src=" props.item.picture" alt="" style="width: 80px;height: 60px"/>-->
                    <v-img
                            width="80px"
                            :src="props.item.picture"
                            aspect-ratio="1"
                            class="grey lighten-2"
                    >
                        <template v-slot:placeholder>
                            <v-layout
                                    fill-height
                                    align-center
                                    justify-center
                                    ma-0
                            >
                                <v-progress-circular indeterminate color="grey lighten-5"></v-progress-circular>
                            </v-layout>
                        </template>
                    </v-img>
                    <div class="play" @click="setSongUrl(props.item.songUrl)">
                        <!--关闭的状态-->
                        <div v-if="toggle !== props.item.songUrl">
                            <span class="iconfont">&#xe602;</span>
                        </div>
                        <!--开启的状态-->
                        <div v-if="toggle === props.item.songUrl">
                            <span class="iconfont">&#xe693;</span>
                        </div>
                    </div>
                </div>
                </td>
                <td class="text-xs-center">{{ props.item.name }}</td>
                <td class="text-xs-center">{{ props.item.singer.name }}</td>
                <td class="text-xs-center">{{ props.item.audioDuration }}分</td>
                <td class="text-xs-center">{{ props.item.count }}</td>
                <td class="text-xs-center">
                <v-tooltip left>
                    <v-btn slot="activator" icon @click="editSong(props.item)">
                        <i class="el-icon-edit"/>
                    </v-btn>
                    <span> 修改歌曲</span>
                </v-tooltip>
                <v-tooltip left>
                    <v-btn icon slot="activator" @click="delSong( props.item.id)">
                        <i class="el-icon-delete"/>
                    </v-btn>
                    <span> 删除歌曲</span>
                </v-tooltip>
                </td>
            </template>
        </v-data-table>
        <!--弹出的对话框-->
        <v-dialog max-width="800" v-model="show" persistent scrollable>
            <v-card>
                <!--对话框的标题-->
                <v-toolbar dense dark color="primary">
                    <v-toolbar-title>{{isEdit ? '修改' : '新增'}}歌曲</v-toolbar-title>
                    <v-spacer/>
                    <!--关闭窗口的按钮-->
                    <v-btn icon @click="closeWindow">
                        <v-icon>close</v-icon>
                    </v-btn>
                </v-toolbar>
                <!--对话框的内容，表单-->
                <v-card-text class="px-3" style="height: 600px">
                    <songs-form
                            @changeSong = "changeSong"
                            @close="closeWindow"
                            :step="step"
                            :is-edit="isEdit"
                            ref="songForm"/>
                </v-card-text>
                <!--底部按钮，用来操作步骤线-->
                <v-card-actions class="elevation-10">
                    <v-flex class="xs3 mx-auto">

                        <div v-if="step === 1">
                        <v-btn @click="previous" color="primary" :disabled="step === 1">上一步</v-btn>
                        <v-btn @click="next" color="primary" :disabled="step === 3">下一步</v-btn>
                        </div>
                        <div v-if="step > 1">
                            <v-btn @click="previous" color="primary" >上一步</v-btn>
                            <v-btn @click="submit" color="primary" >保存</v-btn>
                        </div>
                    </v-flex>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </v-card>
</template>

<script>import SongsForm from './SongForm'
import SongAudio from '../components/SongAudio'
import { mapGetters } from 'vuex'
export default {
data () {
    return {
        search: '',     //搜索条件
        pagination: {
            descending: false,
            page: 1,
            rowsPerPage: 5, // -1 for All",
            sortBy: "",
            totalItems: []
        }, // 分页信息
        isEdit: false,  //是否是修改
        headers: [
            {text: 'id', align: 'left', sortable: false, value: 'id'},
            { text: '图片', value: 'picture', sortable: false,align: 'center'},
            { text: '歌曲名称', value: 'name',align: 'center' },
            { text: '歌手名称', value: 'singer_id' ,align: 'center'},
            { text: '时长', value: 'create_time' ,align: 'center'},
            { text: '播放次数', value: 'count' ,align: 'center'},
            { text: '操作', align: 'center' ,align: 'center'}
        ],
        songs: [],
        totalSongs: 0,
        show: false,
        step: 1,
        toggle: false,
        oldSong:{},
        loading: true,
        timer: 0,
    }
},
    methods: {
    getDataFromServer(){
        this.$http.get("/song/page",{
            params: {
                key: this.search,
                page: this.pagination.page,
                rows: this.pagination.rowsPerPage,
                sortBy: this.pagination.sortBy? this.pagination.sortBy :"",
                desc: this.pagination.descending? this.pagination.descending:"true"
            }
        }).then(resp =>  {
            console.log(resp.data)
            this.songs = resp.data.items;
            this.totalSongs = resp.data.total;
            this.loading = false;
        }).catch(()=>{
            this.songs = [];
            this.totalSongs = 0;
            this.loading = false;
        })
    },
    closeWindow() {
        // 重新加载数据
        this.getDataFromServer();
        // 关闭窗口
        this.show = false;
        // 将步骤调整到1
        this.step = 1;
    },
     previous() {
        this.step--
     },
     next() {
        this.step++
     },
     addSong() {
         this.isEdit = false
         this.show = true
         this.oldSong = null
         // this.$refs.songForm.reset()
         this.$refs.songForm.songform = {
             picture: "",
             songUrl: "",
             audioDuration: 0,
             lyric: "",
         }
     },
     editSong(oldSong) {
          this.$http.get("category/song/of/findBySid?id="+oldSong.id).then(resp=>{
              oldSong.categories = resp.data
              this.$refs.songForm.songform=oldSong
              console.log(oldSong)
              this.isEdit = true
              this.show = true
          })
      },
     setSongUrl (url) {
          this.$store.commit('setUrl', url)
          // 如果isPlay为false则不播放音乐
          if (this.toggle === url) {
              this.$store.commit('setIsPlay', false)
              this.toggle = ''
          } else {
              this.$store.commit('setIsPlay', true)
              //这里的url到时是从对象里取的
              this.toggle = url
          }
          console.log(this.toggle +"songs页面的toggle")
      },
     submit() {
          const {categories,singer, ...params} = this.oldSong
          console.log(categories)
          params.cids = categories.map(c => c.id).join(",");
          params.singerId = singer.id;
          //this.$qs.stringfy 可以把对象序列化成字符串{ id: 12345, age: 18 } 序列化为 id=12345&age=18
            this.$http({
                method: this.isEdit?'put':'post',
                url: "/song/saveSong",
                data: this.$qs.stringify(params)
            }).then(()=>{
                // 成功，关闭窗口
                this.$emit("close");
                // 提示成功
                this.$message.success("保存成功");
                //关闭窗口
                this.closeWindow();
            })
                .catch(error => {
                    console.log(error)
                    this.$message.error("保存失败！");});
        },
     changeSong(obj) {
            this.oldSong = obj
            console.log("song页面oldSong父组件"+this.oldSong)
        },
     //设值定时器
     searchEvent() {
            this.clearTimer();
            if (this.search && this.search.length > 0) {
                this.timer = setTimeout(() =>{
                    this.getDataFromServer();
                },500)
            }else {
                this.getDataFromServer();
            }
        },
     clearTimer() {
            if (this.timer) {
                clearTimeout(this.timer);
            }
        },
     //删除
     delSong(id) {
            this.$message.confirm("你确定删除改歌曲嘛").then(()=>{
                this.$http.get("/song/delete/"+id)
                    .then(()=>{
                        this.$message.success("删除成功")
                        this.getDataFromServer();
                    })
                    .catch(()=>{
                        this.$message.error("删除失败")
                    })
            })
        },
    },
    computed: {
        ...mapGetters([
            'isPlay' // 播放状态
        ])
    },
    components: {
        SongAudio,
        SongsForm
    },
    watch:{
        //留个Bug，歌曲播放完后图标不变回初始状态
        pagination: {
            deep: true,
            handler() {
                //重新加载数据
                this.getDataFromServer();
            }
        },
        search: {
            handler() {
                //重新加载数据
                this.searchEvent();
            }
        }
    },
    mounted() {
        this.getDataFromServer();
    },
}
</script>
<style scoped>
    .imPlay{
        height: 100px;
        margin: auto;
        padding-top: 10px;
        padding-left: 40px;
    }
    .play{
        position: absolute;
        cursor: pointer;
        margin-top: -6%;
        margin-left: 2.5%;
    }

    .hoveTitle {
        　　text-align: left;
        　　width: 140px;
        　　overflow: hidden;
        　　text-overflow: ellipsis;
        　　white-space: nowrap;
    }
    @font-face {
        font-family: 'iconfont';
        src: url('../../assets/css/font/iconfont.eot');
        src: url('../../assets/css/font/iconfont.eot?#iefix') format('embedded-opentype'),
        url('../../assets/css/font/iconfont.woff2') format('woff2'),
        url('../../assets/css/font/iconfont.woff') format('woff'),
        url('../../assets/css/font/iconfont.ttf') format('truetype'),
        url('../../assets/css/font/iconfont.svg#iconfont') format('svg');
    }
    .handle-box {
        margin-bottom: 20px;
    }
    .handle-input {
        width: 300px;
        display: inline-block;
    }
    .iconfont {
        font-family: "iconfont" !important;
        font-size: 30px;
        font-style: normal;
        color: white;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
    }

    </style>